using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SceneItemManager : MonoBehaviour,ISaveLevelManager
{
    public static SceneItemManager instance;
    private void Awake()
    {
        instance = this;

        //获取物品
        GetAllItem();
    }
    [Header("上下楼点")]
    public Transform upPos;
    public Transform downPos;
    [Header("上下楼梯")]
    public Transform upStair;
    public Transform downStair;
    [Header("楼层id")]
    public int id = 1;
    [Header("场景钥匙")]
    public List<GameObject> keys = new List<GameObject>();
    public float keyWeight = 5;
    [Header("场景敌人")]
    public List<GameObject> enemies = new List<GameObject>();
    [Header("场景门")]
    public List<GameObject> doors = new List<GameObject>();
    [Header("场景NPC")]
    public List<GameObject> npcs = new List<GameObject>();
    [Header("场景Item")]
    public List<GameObject> items = new List<GameObject>();
    [Header("此时点击的敌人")]
    public GameObject clickEnemy = null;
    public bool clickEnemyRight = false;
    [Header("单词门")]
    public GameObject wordDoor;
    [Header("石头门")]
    public GameObject stoneDoor;

    //存储数据
    [Header("敌人数据")]
    public List<EnemyData> enemyDatas = new List<EnemyData>();
    [Header("钥匙数据")]
    public List<bool> keysExist = new List<bool>();
    [Header("门数据")]
    public List<bool> doorsExist = new List<bool>();
    [Header("Npc数据")]//主要针对一次性获取的npc
    public List<bool> npcData = new List<bool>();
    [Header("Item数据")]
    public List<bool> itemData = new List<bool>();
    [Header("单词门数据")]
    public bool wordDoorData = true;
    [Header("石头门数据")]
    public bool stoneDoorData = true;

    public IEnumerator Init()
    {
        yield return new WaitForSeconds(0.1f);

        LoadData();
        //设置死亡墓碑
        SetPlayerDieObj();
        //获取玩家动画
        GameManager.Instance.player.GetAniMaterial();
        //设置钥匙权重
        SetKeyWeight();
        //设置Item权重
        SetItemWeight();
        //设置敌人阻挡
        SetEnemyStop();
        //设置玩家位置
        SetPlayerPos();
        //设置门阻挡
        SetDoorStop();
        //设置Npc
        SetNpcStop();
        //到达可以传送
        OnArrive();
        //设置单词门
        OnSetWordDoor();
        //设置石头门
        SetStoneDoor();
        //设置楼梯权重
        SetStairWeight();
        //更新符文
        TurnManager.instance.UpdateModify();
        //只有不为空才设置
        if (WaterMapManager.instance!=null)
        {
            //幽灵状态才能过去
            if(GameManager.Instance.playerDieData.isDie)
            {
                WaterMapManager.instance.SetRun();
            }
            else
            {
                WaterMapManager.instance.SetStop();
            }
        }
        //设置名称
        GameManager.Instance.UpdateMainName("战塔 --- <color=yellow>"+id+" </color>层");

        StartCoroutine(Arrive0Layer());
    }
    //设置玩家死亡墓碑
    public void SetPlayerDieObj()
    {
        if(GameManager.Instance.playerDieData!=null&&GameManager.Instance.playerDieData.isDie)
        {
            if(GameManager.Instance.playerDieData.levelId==id)
            {
                GameObject newObj = Instantiate(PoolManager.Instance.playerDieObj);
                newObj.transform.SetParent(transform);
                newObj.transform.position=GameManager.Instance.playerDieData.diePos;
            }
        }
    }
    //设置楼梯权重
    public void SetStairWeight()
    {
        if(upStair)
        {
            SetWeight(upStair, 9);
        }
        if(downStair)
        {
            SetWeight(downStair, 9);
        }
    }
    //检测第一次到达0层
    public IEnumerator Arrive0Layer()
    {
        yield return new WaitForSeconds(1f);

        if(id==0)
        {
            AchiManager.instance.UnLockAchi("战塔");
        }
        else if(id==60)
        {
            AchiManager.instance.UnLockAchi("高处的风景");
        }
    }
    //到达后可以传送
    public void OnArrive()
    {
        if(id>0&&id<=100)
        {
            GameManager.Instance.unLockLevel[id-1]=true;
        }
    }
    //获取物品（避免一个一个托）
    public void GetAllItem()
    {
        //父物体
        Transform doorTran = transform.Find("Door");
        Transform enemyTran = transform.Find("Enemy");
        Transform keyTran = transform.Find("Key");
        Transform coinTran = transform.Find("Coin");
        Transform itemTran = transform.Find("Item");
        Transform npcTran = transform.Find("Npc");

        //赋值
        for (int i=0;i<doorTran.childCount;i++)
        {
            doors.Add(doorTran.GetChild(i).gameObject);
        }
        for (int i = 0; i<keyTran.childCount; i++)
        {
            keys.Add(keyTran.GetChild(i).gameObject);
        }
        for (int i = 0; i<enemyTran.childCount; i++)
        {
            enemies.Add(enemyTran.GetChild(i).gameObject);
        }
        for (int i = 0; i<npcTran.childCount; i++)
        {
            npcs.Add(npcTran.GetChild(i).gameObject);
        }
        for (int i = 0; i<itemTran.childCount; i++)
        {
            items.Add(itemTran.GetChild(i).gameObject);
        }
    }
    //设置玩家位置
    public void SetPlayerPos()
    {
        if (GameManager.Instance.isUpStair)
        {
            GameManager.Instance.player.transform.position = upPos.position;
        }
        else
        {
            GameManager.Instance.player.transform.position = downPos.position;
        }

        //设置玩家
        StartCoroutine(ShowPlayer());
    }
    //出现玩家
    public IEnumerator ShowPlayer()
    {

        yield return new WaitForSeconds(0.01f);

        //出现玩家
        GameManager.Instance.player.gameObject.SetActive(true);
    }
    //设置场景钥匙权重
    public void SetKeyWeight()
    {
        for(int i=0;i<keysExist.Count;i++)
        {
            if (keysExist[i])
            {
                Vector2Int pos = new Vector2Int(Mathf.RoundToInt(keys[i].transform.position.x),
                Mathf.RoundToInt(keys[i].transform.position.y));
                AStarManager.Instance.SetWeight(pos.x, pos.y, 5);
            }
            else
            {
                keys[i].gameObject.SetActive(false);
            }
        }

        //应用到玩家
        AStarManager.Instance.SetAllAStar();
    }
    //设置场景Item权重
    public void SetItemWeight()
    {
        for (int i = 0; i<itemData.Count; i++)
        {
            if (itemData[i])
            {
                Vector2Int pos = new Vector2Int(Mathf.RoundToInt(items[i].transform.position.x),
                Mathf.RoundToInt(items[i].transform.position.y));
                AStarManager.Instance.SetWeight(pos.x, pos.y, 5);
            }
            else
            {
                items[i].gameObject.SetActive(false);
            }
        }

        //应用到玩家
        AStarManager.Instance.SetAllAStar();
    }
    //去掉权重
    public void ReWeight(GameObject obj)
    {
        Vector2Int pos = new Vector2Int(Mathf.RoundToInt(obj.transform.position.x),
       Mathf.RoundToInt(obj.transform.position.y));
        AStarManager.Instance.SetWeight(pos.x, pos.y, 0);
    }
    //移除钥匙列表
    public void ReKeyList(GameObject obj)
    {
        //找到钥匙索引，设置存储
        int index = -1;
        for(int i=0;i<keys.Count;i++)
        {
            if (obj==keys[i])
            {
                index=i;
                break;
            }
        }
        if(keysExist.Count>index)
        {
            keysExist[index]=false;
        }
        if (keys.Contains(obj))
        {
            //keys.Remove(obj);
            ReWeight(obj);
        }
        //应用到玩家
        AStarManager.Instance.SetAllAStar();
    }
    //移除Item列表
    public void ReItemList(GameObject obj)
    {
        if (!items.Contains(obj)) return;
        //找到钥匙索引，设置存储
        int index = -1;
        for (int i = 0; i<items.Count; i++)
        {
            if (obj==items[i])
            {
                index=i;
                break;
            }
        }
        if(itemData.Count>index)
        {
            itemData[index]=false;
        }
        if (items.Contains(obj))
        {
            //items.Remove(obj);
            ReWeight(obj);
        }
        //应用到玩家
        AStarManager.Instance.SetAllAStar();
    }
    //设置敌人为Enemy
    public void SetEnemyStop()
    {
        for(int i=0;i<enemyDatas.Count;i++)
        {
            if (enemyDatas[i].isDie==false)
            {
                enemies[i].GetComponent<Enemy>().SetPosEnemy();
                enemies[i].GetComponent<Enemy>().SetSculpture();
            }
            else
            {
                enemies[i].SetActive(false);
            }
        }
    }
    //移除敌人
    public void ReEnemy(Transform obj)
    {
        int index = -1;
        for (int i = 0; i<enemies.Count; i++)
        {
            if (obj.gameObject==enemies[i])
            {
                index=i;
                break;
            }
        }
        if(obj!=null&&enemyDatas.Count>index&&index!=-1)
        {
            enemyDatas[index].isDie=true;
        }
        //enemies.Remove(obj.gameObject);
        obj.gameObject.GetComponent<Enemy>().data.isDie=true;
    }
    //设置点击敌人
    public void SetClickEnemy(GameObject enemy)
    {
        if(clickEnemy)
        {
            ClearClickEnemy();
        }
        clickEnemy = enemy;
        OpenColl();
    }
    //打开点击的碰撞
    public void OpenColl()
    {
        if (clickEnemy)
        {
            if (clickEnemy.GetComponent<Enemy>()!=null)
            {
                clickEnemy.GetComponent<Enemy>().collObj.GetComponent<Collider2D>().enabled = true;
            }
            else if (clickEnemy.GetComponent<Door>() != null)
            {
                clickEnemy.GetComponent<Door>().collObj.GetComponent<Collider2D>().enabled = true;
            }
            else if (clickEnemy.GetComponent<ShopMan>() != null)
            {
                clickEnemy.GetComponent<ShopMan>().collObj.GetComponent<Collider2D>().enabled = true;
            }
            else if (clickEnemy.GetComponent<LoveMan>() != null)
            {
                clickEnemy.GetComponent<LoveMan>().collObj.GetComponent<Collider2D>().enabled = true;
            }
            else if (clickEnemy.GetComponent<LightMan>() != null)
            {
                clickEnemy.GetComponent<LightMan>().collObj.GetComponent<Collider2D>().enabled = true;
            }
        }
    }
    //清空点击敌人
    public void ClearClickEnemy()
    {
        if(clickEnemy)
        {
            if(clickEnemy.GetComponent<Enemy>()!=null)
            {
                clickEnemy.GetComponent<Enemy>().collObj.GetComponent<Collider2D>().enabled = false;
            }
            else if(clickEnemy.GetComponent<Door>() != null)
            {
                clickEnemy.GetComponent<Door>().collObj.GetComponent<Collider2D>().enabled = false;
            }
            else if (clickEnemy.GetComponent<ShopMan>() != null)
            {
                clickEnemy.GetComponent<ShopMan>().collObj.GetComponent<Collider2D>().enabled = false;
            }
            else if (clickEnemy.GetComponent<LoveMan>() != null)
            {
                clickEnemy.GetComponent<LoveMan>().collObj.GetComponent<Collider2D>().enabled = false;
            }
            else if (clickEnemy.GetComponent<LightMan>() != null)
            {
                clickEnemy.GetComponent<LightMan>().collObj.GetComponent<Collider2D>().enabled = false;
            }
            else if (clickEnemy.GetComponent<StatusOfWarrior>() != null)
            {
                clickEnemy.GetComponent<StatusOfWarrior>().collObj.GetComponent<Collider2D>().enabled = false;
            }
            else if (clickEnemy.GetComponent<MouseMan>() != null)
            {
                clickEnemy.GetComponent<MouseMan>().collObj.GetComponent<Collider2D>().enabled = false;
            }
            else if (clickEnemy.GetComponent<Book>() != null)
            {
                clickEnemy.GetComponent<Book>().collObj.GetComponent<Collider2D>().enabled = false;
            }
            else if (clickEnemy.GetComponent<TowerMan>() != null)
            {
                clickEnemy.GetComponent<TowerMan>().collObj.GetComponent<Collider2D>().enabled = false;
            }
            else if (clickEnemy.GetComponent<BloodOfMoonItem>() != null)
            {
                clickEnemy.GetComponent<BloodOfMoonItem>().collObj.GetComponent<Collider2D>().enabled = false;
            }
            else if (clickEnemy.GetComponent<PoisonItem>() != null)
            {
                clickEnemy.GetComponent<PoisonItem>().collObj.GetComponent<Collider2D>().enabled = false;
            }
            else if (clickEnemy.GetComponent<FinalSword>() != null)
            {
                clickEnemy.GetComponent<FinalSword>().collObj.GetComponent<Collider2D>().enabled = false;
            }
        }
        clickEnemy = null;
    }
    //设置门为阻挡
    public void SetDoorStop()
    {
        //设置门为阻挡
        for(int i=0;i<doorsExist.Count;i++)
        {
            if (doorsExist[i])
            {
                SetEnemy(doors[i].transform);
            }
            else
            {
                doors[i].SetActive(false);
            }
        }
        //应用到玩家
        AStarManager.Instance.SetAllAStar();
    }
    //设置Npc为阻挡
    public void SetNpcStop()
    {
        //设置门为阻挡
        for (int i = 0; i<npcData.Count; i++)
        {
            if (npcData[i])
            {
                SetEnemy(npcs[i].transform);
            }
            else
            {
                npcs[i].SetActive(false);
                //SetEnemy(npcs[i].transform);
            }
        }
        //应用到玩家
        AStarManager.Instance.SetAllAStar();
    }
    //获取Npc数据
    public bool GetNpcData(string str)
    {
        for(int i=0;i<npcs.Count;i++)
        {
            if (npcs[i].GetComponent<Npc>().npcName==str)
            {
                return npcData[i];
            }
        }

        return false;
    }
    //设置npc完成
    public void SetNpcFanish(string str)
    {
        for (int i = 0; i<npcs.Count; i++)
        {
            if (npcs[i].GetComponent<Npc>().npcName==str)
            {
                npcData[i]=false;
                return;
            }
        }
    }
    //移除门
    public void ReDoor(Transform door)
    {
        if (door==null&&!doors.Contains(door.gameObject)) return;
        //找到门索引
        int index = -1;
        for (int i = 0; i<doors.Count; i++)
        {
            if (door.gameObject==doors[i])
            {
                index=i;
                break;
            }
        }
        //设置存储
        doorsExist[index]=false;

        //doors.Remove(door.gameObject);
        door.gameObject.SetActive(false);
        //生成特效
        GameObject effect = null;
        if(door.GetComponent<Door>().isLR)
        {
            effect = PoolManager.Instance.GetDoorEffectLr();
        }
        else
        {
           effect = PoolManager.Instance.GetDoorEffectUd();
        }
        effect.transform.position = door.position;
        //去除阻挡
        SetRun(door);
        //应用到玩家
        AStarManager.Instance.SetAllAStar();
    }
    //设置单词门
    public void OnSetWordDoor()
    {
        if(wordDoor!=null)
        {
            if(wordDoorData==false)
            {
                wordDoor.SetActive(false);
            }
            else
            {
                //设置此为阻挡
                SetStop(wordDoor.transform);
                //添加权重
                wordDoor.GetComponent<LevelWordDoor>().SetWeight();
            }
        }
    }
    //单词门完成
    public void OnFanishWordDoor()
    {
        if(wordDoor!=null)
        {
            //可以行走
            SetRun(wordDoor.transform);
            //消失
            wordDoor.SetActive(false);
            //false
            wordDoorData = false;
            //解除权重
            wordDoor.GetComponent<LevelWordDoor>().DeWeight();
        }
    }
    //设置石头门
    public void SetStoneDoor()
    {
        if (stoneDoor == null) return;

        if(stoneDoorData)
        {
            //设置阻挡
            SetStop(stoneDoor.transform);
        }
        else
        {
            stoneDoor.SetActive(false);
        }
    }
    //石头门完成
    public void StoneDoorFanish()
    {
        //关闭石头门
        stoneDoor.SetActive(false);
        stoneDoorData = false;
        //设置可以行走
        SetRun(stoneDoor.transform);
    }
    //设置阻挡
    public void SetStop(Transform obj)
    {
        //去除阻挡
        Vector2Int pos = new Vector2Int(Mathf.RoundToInt(obj.position.x), Mathf.RoundToInt(obj.position.y));
        AStarManager.Instance.SetStop(pos.x, pos.y);
    }
    //设置敌人
    public void SetEnemy(Transform obj)
    {
        //去除阻挡
        Vector2Int pos = new Vector2Int(Mathf.RoundToInt(obj.position.x), Mathf.RoundToInt(obj.position.y));
        AStarManager.Instance.SetEnemy(pos.x, pos.y);
    }
    //设置Run
    public void SetRun(Transform obj)
    {
        //去除阻挡
        Vector2Int pos = new Vector2Int(Mathf.RoundToInt(obj.position.x), Mathf.RoundToInt(obj.position.y));
        AStarManager.Instance.SetRun(pos.x, pos.y);
    }
    //设置权重
    public void SetWeight(Transform obj,float weight)
    {
        //去除阻挡
        Vector2Int pos = new Vector2Int(Mathf.RoundToInt(obj.position.x), Mathf.RoundToInt(obj.position.y));
        AStarManager.Instance.SetWeight(pos.x, pos.y,weight);
    }
    //给此层其他敌人造成伤害
    public void OtherEnemyBeHurt(int _damage,Enemy _enemy)
    {
        //必须是活着的
        for(int i=0;i<enemies.Count;i++)
        {
            Enemy enemy = enemies[i].GetComponent<Enemy>();
            if(enemy!=null&&enemy.data.isDie==false&&enemy.gameObject.activeSelf&&enemy!=_enemy)
            {
                enemy.BeHurt(_damage,false);
            }
        }
    }
    public void Save(ref LevelData data)
    {
        Debug.Log("保存了数据："+id);

        if(data==null)
        {
            data=new LevelData();
        }
        //赋值敌人
        for (int i = 0; i < enemyDatas.Count; i++)
        {
            enemyDatas[i] = enemies[i].GetComponent<Enemy>().data;
        }

        data.allDoor=doorsExist;
        data.allKey=keysExist;
        data.allEnemy=enemyDatas;
        data.npcData=npcData;
        data.itemData=itemData;
        data.wordDoorData = wordDoorData;
        data.stoneDoorData = stoneDoorData;
    }
    public void Load(LevelData data)
    {
        if (id!=GameManager.Instance.currLevelObj.GetComponent<SceneItemManager>().id) return;
        if(data!=null)
        {
            //foreach (var i in data.allEnemy)
            //{
            //    Debug.Log(i.myName + " / " + i.currHp);
            //}
            doorsExist =data.allDoor;
            keysExist=data.allKey;
            enemyDatas=data.allEnemy;
            npcData=data.npcData;
            itemData=data.itemData;
            wordDoorData = data.wordDoorData;
            stoneDoorData = data.stoneDoorData;

            Debug.Log("加载数据的楼层：" + id);
            //如果敌人为空，直接返回
            if (enemies!=null&&enemies.Count>0&&data.allEnemy!=null&&data.allEnemy.Count>0)
            {
                Debug.Log(data.allEnemy[0].myName + " / " + enemies[0].GetComponent<Enemy>().data.myName + " / " + enemies.Count + " / " + data.allEnemy.Count);
                if (data.allEnemy[0].myName != enemies[0].GetComponent<Enemy>().data.myName
                    ||data.allEnemy.Count!=enemies.Count) return;
                int currNum = enemies.Count;
                if (data.allEnemy.Count < enemies.Count) currNum = data.allEnemy.Count;
                for (int i = 0; i < currNum; i++)
                {
                    enemies[i].GetComponent<Enemy>().data = data.allEnemy[i];
                }
            }
            //Debug.Log(enemyDatas.Count+" / "+enemies.Count);
        }
        else
        {
            doorsExist.Clear();
            keysExist.Clear();
            enemyDatas.Clear();
            npcData.Clear();
            itemData.Clear();
            for (int i=0;i<doors.Count;i++)
            {
                doorsExist.Add(true);
            }
            for (int i = 0; i<keys.Count; i++)
            {
                keysExist.Add(true);
            }
            for (int i = 0; i<enemies.Count; i++)
            {
                enemyDatas.Add(enemies[i].GetComponent<Enemy>().data);
            }
            for (int i = 0; i<npcs.Count; i++)
            {
                npcData.Add(true);
            }
            for (int i = 0; i<items.Count; i++)
            {
                itemData.Add(true);
            }

            foreach(var i in enemies)
            {
                i.GetComponent<Enemy>().SetOriData();
            }
        }

        //让所有敌人初始化
        if (enemies.Count<=0) return;
        foreach (var i in enemies)
        {
            if(i!=null)
            {
                Enemy sc = i.GetComponent<Enemy>();
                if (sc!=null)
                {
                    sc.OnInit();
                }
            }
        }
    }
    //保存数据
    public void SaveData()
    {
        SaveManager.instance.SeekLevelDataInterface();
        SaveManager.instance.SaveLevelDataInterface();
        SaveManager.instance.SaveLevelData(Application.persistentDataPath, "Data"+GameManager.Instance.fileNum+"/Level"+id);
    }
    //加载数据
    public void LoadData()
    {
        //加载数据,调用接口
        SaveManager.instance.LoadLevelData(Application.persistentDataPath, "Data" + GameManager.Instance.fileNum + "/Level" + id);
        SaveManager.instance.SeekLevelDataInterface();
        SaveManager.instance.GetLevelDataInterface();

        Debug.Log("调用楼层：" + id);
    }
}